import { VxeUI } from 'vxe-pc-ui';
import { ElTag } from 'element-plus';
import { getNestedPropertyValue } from './utils';

/**
 * 获取属性值的通用函数
 * @param {string} attrName - 属性名
 * @param {*} defaultValue - 默认值
 * @param {Object} sources - 属性来源对象数组
 * @returns {*} 属性值
 */
const getAttributeValue = (attrName, defaultValue, ...sources) => {
  for (const source of sources) {
    if (source && source[attrName] !== undefined) {
      return source[attrName];
    }
  }
  return defaultValue;
};

/**
 * 格式化标签显示值的函数
 * @param {*} value - 原始值
 * @param {Object} renderOpts - 渲染选项
 * @param {Object} props - 属性对象
 * @param {Object} attrs - 特性对象
 * @returns {string} 格式化后的显示值
 */
const formatTagValue = (value, renderOpts, props = {}, attrs = {}) => {
  if (value === null || value === undefined || value === '') {
    return '-';
  }

  // 获取格式化配置
  const formatter = getAttributeValue(
    'formatter',
    null,
    props,
    attrs,
    renderOpts,
  );
  const maxLength = getAttributeValue(
    'maxLength',
    null,
    props,
    attrs,
    renderOpts,
  );

  let displayValue = String(value);

  // 长度限制处理
  if (maxLength && displayValue.length > maxLength) {
    displayValue = displayValue.substring(0, maxLength) + '...';
  }

  // 自定义格式化函数
  if (formatter && typeof formatter === 'function') {
    displayValue = formatter(value);
  }

  return displayValue;
};

/**
 * 渲染标签显示模式的通用函数
 * @param {Object} renderOpts - 渲染选项
 * @param {Object} params - 参数对象
 * @returns {JSX.Element} 渲染结果
 */
const renderTagDisplay = (renderOpts, params) => {
  // 确定有效的数据和列上下文
  const effectiveData = params?.row || renderOpts.row || renderOpts.data || {};
  const effectiveColumn = params?.column || renderOpts.column || {};

  // 获取字段名
  const field =
    effectiveColumn.field || effectiveColumn.property || params?.field;

  if (!field) {
    console.warn('ElTagRender: Missing field identifier in display mode');
    return <span>-</span>;
  }

  // 获取当前值
  const value = getNestedPropertyValue(effectiveData, field);

  // 获取配置信息
  const props = renderOpts.props || {};
  const attrs = renderOpts.attrs || {};

  // 如果值为空，显示默认内容
  if (value === null || value === undefined || value === '') {
    const emptyText = getAttributeValue(
      'emptyText',
      '-',
      props,
      attrs,
      renderOpts,
    );
    return <span style={{ color: '#999' }}>{emptyText}</span>;
  }

  // 格式化显示值
  const displayValue = formatTagValue(value, renderOpts, props, attrs);

  // 获取标签配置
  const type = getAttributeValue('type', '', props, attrs, renderOpts);
  const size = getAttributeValue('size', 'default', props, attrs, renderOpts);
  const effect = getAttributeValue('effect', 'light', props, attrs, renderOpts);
  const color = getAttributeValue('color', '', props, attrs, renderOpts);
  const hit = getAttributeValue('hit', false, props, attrs, renderOpts);
  const round = getAttributeValue('round', false, props, attrs, renderOpts);
  const closable = getAttributeValue(
    'closable',
    false,
    props,
    attrs,
    renderOpts,
  );
  const disableTransitions = getAttributeValue(
    'disableTransitions',
    false,
    props,
    attrs,
    renderOpts,
  );

  // 获取样式配置
  const tagStyle = getAttributeValue('style', {}, props, attrs, renderOpts);
  const className = getAttributeValue('class', '', props, attrs, renderOpts);

  // 构建标签属性
  const tagProps = {
    type,
    size,
    effect,
    color,
    hit,
    round,
    closable,
    disableTransitions,
    style: tagStyle,
    class: className,
  };

  // 过滤掉空值属性
  const filteredProps = Object.fromEntries(
    Object.entries(tagProps).filter(
      ([key, value]) => value !== null && value !== undefined && value !== '',
    ),
  );

  // 返回标签元素
  return <ElTag {...filteredProps}>{displayValue}</ElTag>;
};

/**
 * 通用渲染逻辑函数（用于编辑模式）
 * @param {Object} renderOpts - 渲染选项
 * @param {Object} params - 参数对象
 * @returns {JSX.Element} 渲染结果
 */
const renderElTag = (renderOpts, params) => {
  // 确定有效的数据和项上下文
  const effectiveData = params?.row || params?.data || renderOpts.data || {};
  const effectiveItem = params?.item || renderOpts.item || {};
  const effectiveColumn = params?.column || {};

  // 确定字段名
  const field =
    params?.field ||
    effectiveColumn.field ||
    effectiveItem.field ||
    renderOpts.field;

  if (!field) {
    console.error('ElTagRender: Missing field identifier in edit mode');
    return null;
  }

  // 获取当前值，使用辅助函数支持多层属性访问
  const value = getNestedPropertyValue(effectiveData, field);

  // 从effectiveItem中获取配置信息
  const itemRender = effectiveItem.itemRender || {};
  const props = itemRender.props || renderOpts.props || {};
  const attrs = itemRender.attrs || renderOpts.attrs || {};
  const events = itemRender.events || renderOpts.events || {};

  // 如果值为空，显示默认内容
  if (value === null || value === undefined || value === '') {
    const emptyText = getAttributeValue(
      'emptyText',
      '-',
      props,
      attrs,
      renderOpts,
    );
    return <span style={{ color: '#999' }}>{emptyText}</span>;
  }

  // 格式化显示值
  const displayValue = formatTagValue(value, renderOpts, props, attrs);

  // 事件处理器
  const handleClose = () => {
    // 清空值
    if (params?.row) {
      params.row[field] = '';
    } else if (params?.data) {
      params.data[field] = '';
    } else if (renderOpts.data) {
      renderOpts.data[field] = '';
    }

    // 触发close事件
    events.close?.(effectiveData, params || renderOpts);
  };

  const handleClick = (event) => {
    // 触发click事件
    events.click?.(event, effectiveData, params || renderOpts);
  };

  // 构建标签属性
  const tagProps = {
    // 基础属性
    type: getAttributeValue('type', '', props, attrs, itemRender, renderOpts),
    size: getAttributeValue(
      'size',
      'default',
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    effect: getAttributeValue(
      'effect',
      'light',
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    color: getAttributeValue('color', '', props, attrs, itemRender, renderOpts),
    hit: getAttributeValue('hit', false, props, attrs, itemRender, renderOpts),
    round: getAttributeValue(
      'round',
      false,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    closable: getAttributeValue(
      'closable',
      false,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    disableTransitions: getAttributeValue(
      'disableTransitions',
      false,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),

    // 样式属性
    style: getAttributeValue('style', {}, props, attrs, itemRender, renderOpts),
    class: getAttributeValue('class', '', props, attrs, itemRender, renderOpts),

    // 事件处理
    onClose: handleClose,
    onClick: handleClick,
  };

  // 过滤掉值为null、undefined或空字符串的属性
  const filteredProps = Object.fromEntries(
    Object.entries(tagProps).filter(
      ([key, value]) => value !== null && value !== undefined && value !== '',
    ),
  );

  // 返回ElTag组件
  return <ElTag {...filteredProps}>{displayValue}</ElTag>;
};

// 注册支持多种上下文的渲染器
VxeUI.renderer.add('RaElTagRender', {
  // 表格单元格编辑模式
  renderTableEdit(renderOpts, params) {
    return renderElTag(renderOpts, params);
  },

  // 表格单元格显示模式
  renderTableCell(renderOpts, params) {
    return renderTagDisplay(renderOpts, params);
  },

  // 表单项目渲染
  renderItemContent(renderOpts, params) {
    return renderElTag(renderOpts, params);
  },

  // 默认显示模式（与renderTableCell相同）
  renderDefault(renderOpts, params) {
    return renderTagDisplay(renderOpts, params);
  },
});

export default 'RaElTagRender';
